<?php

/**
 * Methods to manipulate user, without the need of facebook
 * Uses facebookcontroller + moviecontroller
 *
 *	@method rankFriendsByScore()
 *	@method compareScore($a, $b)
 *	@method renderFriendslist()
 *
 * 	@author Jiles
 */

class Usercontroller {
    
    private $dbcon;

    private $handleError = "";
    private $loginSessionVar = "userid";
    
    private $user;
    private $friendids;
    
    private $fbcon;
    private $movcon;

    public function  __construct($_dbcon, $_fbcon, $_movcon)
    {
        $this->dbcon = $_dbcon;
        $this->fbcon = $_fbcon;
        $this->movcon = $_movcon;
    }
       
    /**
    *	Render Friend list: UL
    *
    *	@return HTLM UL LIST
    */
    public function renderFriendsList(){
    	
    	
    	$friends = $this->rankFriendsByScore();
 
    	$output = "<ul>";
    	
  		foreach($friends as $friend){
  			
  			$output .= "<li "; 
  			//if user is not logged in, mock-array from rankFriendsByScore is used
  			//to create 1 list-item. 
  			//mock-item-1 has id==0, equals fb->getUserID if no user is registered (=>create #me)
  			if($friend["id"] == $this->fbcon->getUserID())
  			 	$output .= "id='me'";
  				$output .=  "value='" . $friend["id"] ."'>";
  				$output .= "<span class='name'>". $friend["name"] ." </span>";
  				$output .= "<span class='score'>". $friend["score"] ."</span></li>";	
  		}    	
    	
    	$output .= "</ul>";
    
    	return $output;
    }
    /**
    *	Sort Friends + currentUser by score. Highest score -> lowest score.
    *	
    *	@return array $rankedfriends;
    */
    public function rankFriendsByScore()
    {
    	$friends = $this->fbcon->checkForFriendsInDb();
    	
    	//create MOCK-list for unregistered users
    	if(!$friends)
    	{	$mock_array = array();
    		$mock_array[]= array("id" => 0, "name" => "you", "score" => 0);
    		$mock_array[]= array("id" => 1, "name" => "your friend", "score" => 5);
    		return $mock_array;
    	}
    		
    	$rankedfriends = array();
    	
    	foreach ($friends as $key => $value){
    		$score = $this->movcon->countMoviesFromUser($key);
    		$rankedfriends[$key] = array( "id" => $key, "name" => $value, "score" => $score );    	
    	}
    	
    	usort($rankedfriends, "compareScore");
    	
    	return $rankedfriends;
    
    }
    
    
}

//Compare functions
function compareScore($a, $b){
    
    	$scoreA = $a["score"];
    	$scoreB = $b["score"];
    	
    	if($scoreA == $scoreB)
    	{
    		return 0;
    	}
    	
    	return ($scoreA < $scoreB) ? 1 : -1;
    }
	
?>
